﻿using AvalonAdmin.Helpers;
using AvalonAdmin.ViewModels;
using AvalonAdmin.Views;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using D.Util.UtilNLog;
using System;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin;

public partial class App : Application
{
    public App()
    { 
        // 确保应用程序以管理员权限运行
        if (!IsAdministrator())
        {
            MessageBox.ShowAsync("此应用需要管理员权限才能监控网络流量。请右键点击应用程序并选择'以管理员身份运行'。");
            return;
        }

        // 初始化
        AutoFacHelper.Initialize();

        // 异常处理
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
    }
     
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private bool IsAdministrator()
    {
        var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
        var principal = new System.Security.Principal.WindowsPrincipal(identity);
        return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        // Line below is needed to remove Avalonia data validation.
        // Without this line you will get duplicate validations from both Avalonia and CT
        BindingPlugins.DataValidators.RemoveAt(0);

        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            desktop.MainWindow = new LoadingWindow
            {
                DataContext = new SplashViewModel()
            };
        }
        else if (ApplicationLifetime is ISingleViewApplicationLifetime singleViewPlatform)
        {
            //singleViewPlatform.MainView = new SingleView
            //{
            //    DataContext = new SingleViewModel()
            //};
        }

        base.OnFrameworkInitializationCompleted();

        
    }

    #region 系统异常处理

    private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
    {
        HandleException(e.Exception);
        e.SetObserved();
    }

    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        HandleException(e.ExceptionObject as Exception);
    }

    private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        HandleException(e.Exception);
        e.Handled = true;
    }

    private async void HandleException(Exception? exception)
    {
        if (exception is null)
        {
            return;
        }
        else
        {
            await Task.Factory.StartNew(() =>
            {
                var log = AutoFacHelper.Instance.Get<INLogService>();
                log.Error(exception.Message);
            });
            //ShowError(exception.Message);
        }
    }
    #endregion
}


